/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.market.controller.member;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.account.entity.PhonePayment;
import com.rzico.account.service.PhonePaymentService;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.*;
import com.rzico.basics.service.MemberService;
import com.rzico.core.service.SysSequenceService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.jwt.JwtTokenUtil;
import com.rzico.market.entity.PhoneOrder;
import com.rzico.market.service.PhoneOrderItemService;
import com.rzico.market.service.PhoneOrderService;
import com.rzico.market.service.PhoneProductService;
import com.rzico.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 销售单控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-02-17
 */
@Api(description = "豆讯话费订单接口")
@RestController
@RequestMapping("/member/phoneOrder")
public class PhoneOrderMemberController extends BaseController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MemberService memberService;

    @Autowired
    private SysSequenceService sysSequenceService;

    @Autowired
    private PhoneOrderService phoneOrderService;

    @Autowired
    private PhoneOrderItemService phoneOrderItemService;

    @Autowired
    private PhonePaymentService phonePaymentService;

    @Autowired
    private PhoneProductService phoneProductService;

    @Autowired
    public JwtTokenUtil jwtTokenUtil;

    /**
     * 分页查询豆讯话费订单管理
     *
     * @return
     */
    @ApiOperation("分页查询豆讯话费订单管理")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "orderStatus", value = "状态", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "token", value = "验证token", dataType = "String", paramType = "query")
    })
    public CommResult<PhoneOrder> list(String orderStatus, String token, Pageable pageable) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        Member member = memberService.getCurrent();
        if (member==null) {
            return CommResult.error("没有登录");
        }
        if (StringUtils.isNotEmpty(token)){
            Map<String,String> sysUser = jwtTokenUtil.getUserInfoFromToken(token);
            Map<String, Object> memberParams = new HashMap<String, Object>();
            memberParams.put("userId", sysUser.get("id").toString());
            List<Member> memberList = memberService.selectList(memberParams);
            if (0 < memberList.size()) {
                params.put("memberId", memberList.get(0).getId());
            }
        }

        if (StringUtils.isNotEmpty(orderStatus)) {
            params.put("orderStatus", orderStatus);
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<PhoneOrder> list = phoneOrderService.selectList(params);
        PageResult<PhoneOrder> pageResult = new PageResult<PhoneOrder>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

    /**
     * 查询单条销售单
     *
     * @return
     */
    @ApiOperation("查询单条销售单")
    @GetMapping("/find/{id}")
    public CommResult<PhoneOrder> find(@PathVariable Long id) {

        PhoneOrder result = phoneOrderService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("order",result);
        result.setItemList(phoneOrderItemService.getItemList(result.getId()));

        Map<String,Object> paymentParams = new HashMap<>();
        paymentParams.put("orderType",0);
        paymentParams.put("orderId",id);
        paymentParams.put("success",1);
        data.put("payments",phonePaymentService.selectList(paymentParams));

        Map<String,Object> params = new HashMap<>();
        params.put("orderId",id);
        params.put("sortField","id");
        params.put("sortType","desc");
        data.put("orderLog",phonePaymentService.selectList(params));

        return CommResult.success(data);
    }

    /**
     * 创建订单
     *
     * @param phoneOrder
     * @return
     */
    @ApiOperation("创建订单")
    @PostMapping("/create")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uuid", value = "用户ID", dataType = "Integer", paramType = "query")
    })
    public CommResult<PhoneOrder> create(@RequestBody PhoneOrder phoneOrder,String uuid) {

        logger.info(">>>>>>>>>>>>>>>>保存订单 start <<<<<<<<<<<<<<<<<");
        logger.info("保存订单参数：[{}]", phoneOrder.toString());
        Assert.notNull(phoneOrder, "订单参数为空");
        Assert.notNull(phoneOrder.getItemList(), "请选购商品");

        Member member = memberService.getCurrent();
        if (member==null) {
            return CommResult.error("没有登录");
        }

        //检测商品库存
        Map<String, Object> checkResultMap = phoneProductService.checkStock(phoneOrder.getItemList().get(0).getProductId());
        if ("fail".equals(checkResultMap.get("check_result"))) {
            return CommResult.error("产品库存不足!");
        }

        phoneOrder.setSn("wangyue" + sysSequenceService.generate("phoneOrder"));
        phoneOrder.setMemberId(member.getId());
        phoneOrder.setEnterpriseId(member.getEnterpriseId());

        try {
            int affectCount = phoneOrderService.insertOrder(phoneOrder);
            if (affectCount <= 0) {
                return CommResult.error();
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return CommResult.error(e.getMessage());
        }

        PhoneOrder result = phoneOrderService.findById(phoneOrder.getId());
        result.setItemList(phoneOrderItemService.getItemList(result.getId()));

        logger.info(">>>>>>>>>>>>>>>>保存订单 end <<<<<<<<<<<<<<<<<");
        return CommResult.success(result);
    }


    /**
     * 订单付款
     *
     * @param id
     * @return
     */
    @ApiOperation("订单付款")
    @PostMapping("/payment/{id}")
    public CommResult<PhoneOrder> payment(@PathVariable Long id) {
        PhoneOrder phoneOrder = phoneOrderService.findById(id);
        if (phoneOrder==null) {
            return CommResult.error("无效付款单号");
        }
        if (phoneOrder.getCreateDate().before(DateUtils.addMinutes(new Date(),-30))) {
            return CommResult.error("超时订单不能付款");
        }
        String sn = sysSequenceService.generate("phonePayment");
        PhonePayment payment = phoneOrderService.payment(phoneOrder,sn);
        System.out.println("=====phonePayment end");
        return CommResult.success(payment);
    }

    /**
     * 批量删除销售单
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除销售单", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除销售单,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<PhoneOrder> del(@PathVariable String ids) {
        phoneOrderService.deleteByIds(ids.split(","));
        return CommResult.success();
    }


}
